const constants = require('../data/constants');
const fs = require('fs');
const gm = require('gm');
const alertModel = require('../model/alerts');
const timingModel = require('../model/timing');
const chokidar = require('chokidar');
const log4js     = require('../data/log');
const logger     = log4js.getLogger('info');
const fileUtils  = require('../utils/fileUtils');

/**
 * 报警文件夹处理
 */
let Alerts={
    init(){
        let path = constants.alertBasePath;
        let ret = true;
        if(!path){
            ret =false;
        }else {
            // 文件夹是否存在
            if (!fs.existsSync(path)) {
                try {
                    fileUtils.makeDir(path);
                    Alerts.readDirSync(path);
                    ret = true;
                } catch (e) {
                    ret = false;
                }
            }else{
                ret = true;
            }
            if(ret){
                Alerts.readDirSync(path);
            }
        }
        logger.info(`初始化报警文件夹,路径：${constants.alertBasePath} 返回值:${ret}`);
        return ret;
    },
    readDirSync(path){
        const pa = fs.readdirSync(path);
        pa.forEach(function(ele){
            const info = fs.statSync(Alerts.appendSlash(path) + ele)
            if(info.isDirectory()){
                Alerts.readDirSync(Alerts.appendSlash(path) + ele);
            }else{
                Alerts.oneFile(Alerts.appendSlash(path) + ele);
            }
        })
    },
    inspect(){
        const watcher = chokidar.watch(constants.alertBasePath, {
            ignored: /[\/\\]\./, persistent: true,
            awaitWriteFinish: {
                stabilityThreshold: 2000,
                pollInterval: 100
            }
        });
        watcher
            .on('add', function(path0) {
                Alerts.oneFile(path0);
            });
    },
    /**
     * 单文件处理
     * @param {*} path0
     */
    oneFile(path0){
        // 区分是定时抓拍，还是事件抓拍
        let path = path0.replace(/\\/g,'/');
        let merge = path.replace(Alerts.appendSlash(constants.alertBasePath), '');
        logger.info('处理文件 ' , merge);

        let arr = merge.split('/');
        let brand = arr[0];
        let deviceid = arr[1];
        let channelid = arr[2];
        let filename = arr[3];
        let regex = constants.fileRegex[brand];

        let timeRegex = filename.match(regex.regex);

        if(timeRegex){
            let result={};
            regex.regex_name.forEach((iter,index)=>{
                if(iter){
                    result[iter]=timeRegex[index];
                }
            });
            console.log(result);
            let timeStr = result['year'] +'-'+result['month'] + '-' + result['day'] + ' ' + result['hour']+':'+result['minute'] + ':' + result['second'];
            let time=new Date(timeStr);

            let fileSavePath,urlBase;
            fileSavePath =Alerts.appendSlash(constants.cameraBak.savePath[result.type]) + deviceid + '/' + channelid ;
            urlBase = Alerts.appendSlash(constants.cameraBak.url[result.type])+ deviceid + '/' + channelid;

            let targetSourcePath = fileSavePath + '/source' ;
            let targetThumbPath  = fileSavePath + '/thumb';
            let urlSource = urlBase + '/source' + '/' + filename;
            let urlThumb  = urlBase + '/thumb'  + '/' + filename;

            Alerts.checkDirectory(targetSourcePath);
            Alerts.checkDirectory(targetThumbPath);
            // 文件生成缩略图，放到目标地址
            let targetThumbFile  = targetThumbPath  + '/' + filename;
            let targetSourceFile = targetSourcePath + '/' + filename;
            console.log(targetThumbFile, targetSourceFile,urlSource,urlThumb, result.type);
            Alerts.makeThumb(path0 , targetThumbFile, targetSourceFile,function(thumbRet){
                if(thumbRet){
                    // 如果是AI ， 写入数据库
                    if (result.type === 'AI_OPEN_PLAT') {
                        logger.info('AI触发');
                        alertModel.insertCheck(deviceid, channelid, urlThumb, urlSource, time.getTime()).then((ret) => {
                             logger.info(ret);
                        },(err) => {
                             logger.error('写入数据库error ' , err);
                            // fs.unlink(targetThumbFile);
                            // fs.unlink(targetSourceFile);
                        });
                    } else {
                        logger.info(' 定时截图，写入截图表');
                        timingModel.insertCheck(deviceid,channelid, urlThumb,urlSource,time.getTime()).then((ret)=>{
                            logger.info(ret);
                        },(err)=>{
                            logger.error(err);
                        });
                    }
                }
            });


        }else{
            logger.error('文件名无法识别', file);
        }
    },
    // 如果url最后不是/就补一个/
    appendSlash(url){
        if (!url) {
            return url;
        }
        if (url.lastIndexOf('/') !== url.length - 1) {
            url = url + '/';
        }
        return url;
    },
    //如果文件夹不存在就创建
    checkDirectory(path){
        let arr = path.split('/');
        let merge='';
        for (let i = 0; i < arr.length; i++) {
            if (!arr[i]) {
                merge = '/';
            } else {
                merge = merge + arr[i] + '/';
            }
            if (merge !== '/') {
                if (!fs.existsSync(merge)) {
                    logger.log('自动创建文件夹', merge);
                    fs.mkdirSync(merge);
                }
            }
        }
    },
    // 制作缩略图
    makeThumb(file,targetThumbFile,targetSourceFile,callback){
        if(fs.existsSync(file)){
            gm(file)
                .resize(150,150,"!")
                .write(targetThumbFile,function(err){
                    if(err){
                        logger.error('生成缩略图错误', file);
                        callback(false);
                    }else{
                        logger.info('生成缩略图成功', file);
                        // 移动文件
                        if(fs.existsSync(file)){
                            fs.renameSync( file, targetSourceFile);
                        }
                        callback(true);
                    }
                })
        }
    }
};

module.exports=Alerts;
